package com.epalmpay.service.activity.impl;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.annotation.Resource;

import com.epalmpay.status.Rescode;
import com.epalmpay.dto.system.BaseOutDTO;
import com.epalmpay.dto.activity.*;
import com.epalmpay.entity.*;
import com.epalmpay.enumdef.ActivityEnum;
import com.epalmpay.enumdef.BizEnum;
import com.epalmpay.mapper.*;
import com.epalmpay.service.activity.IActivityBaseService;
import com.epalmpay.service.activity.ICouponUserService;
import com.epalmpay.service.activity.IRedPackageUserService;
import com.epalmpay.service.groupaccount.impl.GroupAccountServiceImpl;
import com.epalmpay.util.AmountUtils;
import com.epalmpay.util.Logger;
import com.epalmpay.util.PropertyCopyUtil;
import com.epalmpay.util.Tools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;

import com.epalmpay.dto.activity.ActivityUnroutineInDTO;
import com.epalmpay.dto.activity.RedpackageCouponOutDTO;
import com.epalmpay.dto.activity.RedpackageCouponQueryDTO;
import com.epalmpay.dto.activity.UnroutineInDTO;
import com.epalmpay.dto.activity.UnroutineOutDTO;
import com.epalmpay.entity.ActivityBase;
import com.epalmpay.entity.ActivityUnroutine;
import com.epalmpay.entity.ActivityUnroutineRule;
import com.epalmpay.entity.Page;
import com.epalmpay.entity.Redpackage;
import com.epalmpay.mapper.ActivityBaseMapper;
import com.epalmpay.mapper.ActivityUnroutineMapper;
import com.epalmpay.mapper.ActivityUnroutineRuleMapper;
import com.epalmpay.mapper.CouponMapper;
import com.epalmpay.mapper.RedpackageMapper;
import com.epalmpay.service.activity.IActivityUnroutineService;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;



@Service("activityUnroutineService") 
public class ActivityUnroutineServiceImpl implements IActivityUnroutineService {
	protected Logger logger = Logger.getLogger(this.getClass());

	@Resource  
    private ActivityUnroutineMapper activityUnroutineMapper;

	@Autowired
	private RedpackageMapper redpackageMapper;
	@Autowired
	private CouponMapper couponMapper;

	@Autowired
	private ActivityBaseMapper activityBaseMapper;
	@Autowired
	private ActivityUnroutineRuleMapper activityUnroutineRuleMapper;
	@Autowired
	private ActivityUnroutineShopPlusMapper activityUnroutineShopPlusMapper;
	@Autowired
	private TradeOfflineMapper tradeOfflineMapper;
	@Resource
	private OrderServiceGoodMapper orderServiceGoodMapper;
	@Resource
	private MemberMapper memberMapper;
	@Resource
	private IRedPackageUserService redPackageUserService;
	@Resource
	private ICouponUserService couponUserService;
	@Resource
	private RedpackageUserMapper redpackageUserMapper;
	@Resource
	private CouponUserMapper couponUserMapper;
	@Resource
	private BonusSendLogMapper bonusSendLogMapper;
	@Resource
	private ShopGroupRelationMapper shopGroupRelationMapper;
	@Resource
	private BonusVerifyRuleMapper bonusVerifyRuleMapper;

	@Resource
	private MallGoodMapper mallGoodMapper;

	@Resource
	private MallEntityGoodMapper mallEntityGoodMapper;

	@Resource
	private GroupAccountServiceImpl groupAccountService;
	@Resource
	private IActivityBaseService activityBaseService;
	@Resource(name="transactionManager")
	private DataSourceTransactionManager transactionManager;


	public List<UnroutineOutDTO> getUnroutineList(UnroutineInDTO unroutineInDTO,Page page) throws Exception{
		
		Map<String,Object> param=new HashMap<String,Object>();
		param.put("groupId", unroutineInDTO.getGroupId());
		param.put("platformType", unroutineInDTO.getPlatformType());
		param.put("activityStatus", unroutineInDTO.getActivityStatus());
		param.put("startDate", unroutineInDTO.getStartDate());
		param.put("endDate", unroutineInDTO.getEndDate());
		param.put("name", unroutineInDTO.getName());
		
		List<UnroutineOutDTO> result = new ArrayList<UnroutineOutDTO>();

		int sumCount = activityUnroutineMapper.selectActivityListCount(param);
		page.setTotalResult(sumCount);
		if(sumCount<=0)
			return null;
		
		param.put("limit", page.getShowCount());
		param.put("start", page.getShowCount()*(page.getCurrentPage()-1));

		List<Map<String,Object>> unroutineList;
		if(unroutineInDTO.getAgentId() != null) {	//代理商后台查看筛选
			Set<Long> activityIds = new HashSet<>();
			List<Long> shopIds = shopGroupRelationMapper.listShopIdByAgentId(unroutineInDTO.getAgentId());
			for(int i = 0; i < shopIds.size(); i++) {
				List aulist = activityUnroutineMapper.selectShopParticipation(shopIds.get(i).toString());
				if(aulist !=null && aulist.size() >0) {
					activityIds.addAll(aulist);
				}
			}
			if(shopIds.isEmpty()) {
				unroutineList = new ArrayList<>();
			} else {
				if(activityIds.size() > 0) {
					param.put("activityIds", activityIds);
				}
				unroutineList = activityUnroutineMapper.selectActivityList(param);
			}
		} else {	//渠道后台查看
			unroutineList = activityUnroutineMapper.selectActivityList(param);
		}
		
		for (Map<String, Object> unroutine : unroutineList) {
			UnroutineOutDTO unroutineOutDTO = new UnroutineOutDTO();
			unroutineOutDTO.setId((Long) unroutine.get("id"));
			unroutineOutDTO.setActivityName((String)unroutine.get("activity_name"));
			unroutineOutDTO.setActivityPlatformType((Integer)unroutine.get("activity_platform_type"));
			unroutineOutDTO.setCreateUserId((Long)unroutine.get("create_user_id"));
			unroutineOutDTO.setUserName((String)unroutine.get("username"));
			unroutineOutDTO.setPriority((Integer)unroutine.get("priority"));
			unroutineOutDTO.setUserGradeList((String)unroutine.get("user_grade_list"));
			unroutineOutDTO.setGradeNameList((String)unroutine.get("grade_name_list"));
			unroutineOutDTO.setActivityType((Integer)unroutine.get("activity_type"));
			unroutineOutDTO.setStartTime((Date)unroutine.get("start_time"));
			unroutineOutDTO.setEndTime((Date)unroutine.get("end_time"));
			unroutineOutDTO.setShopCount((Integer)unroutine.get("shop_count"));
			unroutineOutDTO.setStatus((Integer)unroutine.get("status"));
//			unroutineOutDTO.setSendType((byte)(int) unroutine.get("send_type"));
			
			result.add(unroutineOutDTO);
		}
		
		return result;
	}

	public List<RedpackageCouponOutDTO> listRedpackageCoupon(RedpackageCouponQueryDTO redpackageCouponQueryDTO) throws Exception {
		List<RedpackageCouponOutDTO> redpackageCouponOutDTOList = new ArrayList<RedpackageCouponOutDTO>();

		String endTimeStr = redpackageCouponQueryDTO.getEndTime();
		Date endTime = null;
		if(endTimeStr != null) {
			DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			endTime = dateFormat.parse(endTimeStr);
		}

		if(redpackageCouponQueryDTO.getSendType() == 2) {
			List<Redpackage> redpackageList = redpackageMapper.selectRedpackages(redpackageCouponQueryDTO.getGroupId(),
					ActivityEnum.PurposeType.UnRoutine.getType(), endTime);
			for(int i = 0; i < redpackageList.size(); i++) {
				RedpackageCouponOutDTO redpackageCouponOutDTO = new RedpackageCouponOutDTO();
				redpackageCouponOutDTO.setId(redpackageList.get(i).getId());
				redpackageCouponOutDTO.setName(redpackageList.get(i).getName());
				redpackageCouponOutDTO.setValue(redpackageList.get(i).getFaceValue());
				redpackageCouponOutDTO.setValidTimeType(redpackageList.get(i).getValidTimeType());
				redpackageCouponOutDTO.setDays(redpackageList.get(i).getAftergetValidtime());
				redpackageCouponOutDTO.setValidEndTime(redpackageList.get(i).getEndGetTime());
				redpackageCouponOutDTO.setUsername(redpackageList.get(i).getUsername());
				redpackageCouponOutDTOList.add(redpackageCouponOutDTO);
			}
		} else if(redpackageCouponQueryDTO.getSendType() == 3) {
			redpackageCouponOutDTOList = couponMapper.selectCoupons(redpackageCouponQueryDTO.getGroupId(),
					ActivityEnum.PurposeType.UnRoutine.getType(), endTime, redpackageCouponQueryDTO.getGoodType());
		}
		return redpackageCouponOutDTOList;
	}

	@Override
	@Transactional
	public BaseOutDTO addUnroutine(ActivityUnroutineInDTO activityUnroutineInDTO) throws Exception {
		Date now = new Date();
		DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		BaseOutDTO baseOutDTO = new BaseOutDTO();
		ActivityBase activityBase = new ActivityBase();
		PropertyCopyUtil.copyProperties(activityUnroutineInDTO, activityBase);
		if(activityUnroutineInDTO.getId() == null) {
			activityBase.setGmtCreate(now);
		}
		activityBase.setGmtModified(now);
		activityBase.setActivityType(ActivityEnum.ActivityType.UnRoutine.getType());	//base表和unrountine表都有ActivityType字段，这里手动设置
		activityBase.setStatus(ActivityEnum.ActivityStatus.Proccessing.getType());	//活动状态设置为进行中
		int i = 0, maxAmountBalance = 0;
		int sendType = activityUnroutineInDTO.getActivityUnroutineRuleList().get(0).getSendType();
		if(activityUnroutineInDTO.getId() == null) {
			i = activityBaseMapper.insertSelective(activityBase);
			if(sendType == ActivityEnum.ActivitySendType.Bonus.getType() || sendType == ActivityEnum.ActivitySendType.Cash.getType()) {
				maxAmountBalance = activityBase.getMaxAmount();
			}
		} else {
			if(sendType == ActivityEnum.ActivitySendType.Bonus.getType() || sendType == ActivityEnum.ActivitySendType.Cash.getType()) {
				maxAmountBalance = activityBaseMapper.getActivityMaxAmountById(activityBase.getId()) - activityBase.getMaxAmount();
			}
			i = activityBaseMapper.updateByPrimaryKeySelective(activityBase);
		}


		if(maxAmountBalance != 0 && sendType == ActivityEnum.ActivitySendType.Cash.getType()) {
//			if(sendType == ActivityEnum.ActivitySendType.Bonus.getType()) {	//如果是积分 则计算相应的金额
//				BonusVerifyRule bonusVerifyRule = bonusVerifyRuleMapper.getDefaultByGroupId(activityBase.getGroupId());
//				if(bonusVerifyRule == null) {
//					throw new ApplicationException("还未设置积分核销风控规则");
//				}
//				maxAmountBalance = maxAmountBalance / bonusVerifyRule.getVerifyRate();
//			}
			//增加营销账户冻结金额
			groupAccountService.updateAmount(activityBase.getGroupId(),BizEnum.SaleAccountSubjectType.ConsumeBackCashCreate,
					maxAmountBalance,null,activityBase.getId(),"新增或者修改活动增加营销账户冻结金额");
		}


		//根据线上活动判断，服务商品或者商城商品， goodids 查出对应的shopid
		String shopIdStr = "";
		Integer shopCount = null;
		if (activityUnroutineInDTO.getActivityPlatformType()!=null &&activityUnroutineInDTO.getActivityPlatformType() == ActivityEnum.ActivityPlatformType.OnLine.getType()) {

			String [] goodids = activityUnroutineInDTO.getGoodids().split(",");
			StringBuilder str = new StringBuilder("");

			if (activityUnroutineInDTO.getGoodType() == 1) {
				for (String goodItem : goodids) {
					MallGood mallGood = mallGoodMapper.selectByPrimaryKey2(Long.parseLong(goodItem));

					if(mallGood != null && !str.toString().contains(mallGood.getMshopId()+"")){
						str.append(mallGood.getMshopId()+",");
					}
				}


			}else{
				for (String goodItem : goodids){
					MallEntityGood mallEntityGood = mallEntityGoodMapper.selectByPrimaryKey3(Long.parseLong(goodItem));
					if(mallEntityGood != null &&  !str.toString().contains(mallEntityGood.getShopId()+"")){
						str.append(mallEntityGood.getShopId()+",");
					}
				}
			}

			if (!Tools.isEmpty(str.toString())) {
				shopIdStr = str.toString().substring(0, str.toString().length() - 1);
				String [] shops = shopIdStr.split(",");
				shopCount = shops.length;
			}
		}else{
			shopIdStr = activityUnroutineInDTO.getShopids();
			shopCount = activityUnroutineInDTO.getShopCount();
		}



		if(i == 1) {
			ActivityUnroutine activityUnroutine = new ActivityUnroutine();
			PropertyCopyUtil.copyProperties(activityUnroutineInDTO, activityUnroutine);
			activityUnroutine.setStartTime(dateFormat.parse(activityUnroutineInDTO.getStartTimeStr()));
			activityUnroutine.setEndTime(dateFormat.parse(activityUnroutineInDTO.getEndTimeStr()));
			activityUnroutine.setActivityId(activityBase.getId());
			activityUnroutine.setShopids(shopIdStr);
			activityUnroutine.setShopCount(shopCount);
			activityUnroutine.setSendType(activityUnroutineInDTO.getActivityUnroutineRuleList().get(0).getSendType());
			if(activityUnroutineInDTO.getId() == null) {
				activityUnroutine.setGmtCreate(now);
			}
			activityUnroutine.setGmtModified(now);
			int j = 0;
			if(activityUnroutineInDTO.getId() == null) {
				j = activityUnroutineMapper.insertSelective(activityUnroutine);
			} else {
				j = activityUnroutineMapper.updateByPrimaryKeySelective(activityUnroutine);
			}

			if(j == 1) {
				if(activityUnroutineInDTO.getId() != null) {
					activityUnroutineRuleMapper.deleteByActivityId(activityUnroutineInDTO.getId());
					activityUnroutineShopPlusMapper.deleteByActivityId(activityUnroutineInDTO.getId());
				}
				List<ActivityUnroutineRule> activityUnroutineRuleList = activityUnroutineInDTO.getActivityUnroutineRuleList();
				for(int x = 0; x < activityUnroutineRuleList.size(); x++) {
					ActivityUnroutineRule activityUnroutineRule = new ActivityUnroutineRule();
					PropertyCopyUtil.copyProperties(activityUnroutineRuleList.get(x), activityUnroutineRule);
					activityUnroutineRule.setActivityId(activityBase.getId());
					activityUnroutineRule.setGmtCreate(now);
					activityUnroutineRule.setGmtModified(now);
					activityUnroutineRuleMapper.insertSelective(activityUnroutineRule);
				}
				List<ActivityUnroutineShopPlus> activityUnroutineShopPlusList = activityUnroutineInDTO.getActivityUnroutineShopPlusList();
				if(activityUnroutineShopPlusList != null && activityUnroutineShopPlusList.size() > 0) {
					activityUnroutineShopPlusMapper.insertBatch(activityUnroutineShopPlusList, activityBase.getId(), now);
				}
				baseOutDTO.setErrorCode(Rescode.SUCCESS);
			}
		}
		return baseOutDTO;
	}

	@Override
	public ActivityUnroutineOutDTO getUnroutineActivity(Long id) {
		ActivityUnroutineOutDTO activityUnroutineOutDTO =  activityUnroutineMapper.getUnroutineActivity(id);
		List<ActivityUnroutineRule> activityUnroutineRuleList = activityUnroutineRuleMapper.selectActivityUnroutineRule(id);
//		List<ActivityUnroutineShopPlus> activityUnroutineShopPlusList = activityUnroutineShopPlusMapper.selectActivityUnroutineShopPlusList(id);
		activityUnroutineOutDTO.setActivityUnroutineRuleList(activityUnroutineRuleList);
//		activityUnroutineOutDTO.setActivityUnroutineShopPlusList(activityUnroutineShopPlusList);
		return activityUnroutineOutDTO;
	}
//	@Override
//	public ActivityUnroutineOutDTO getUnroutineActivity(ActivityUnroutineInDTO activityUnroutineInDTO) {
//		ActivityUnroutineOutDTO activityUnroutineOutDTO =  activityUnroutineMapper.getUnroutineActivity(activityUnroutineInDTO);
//		List<ActivityUnroutineRule> activityUnroutineRuleList = activityUnroutineRuleMapper.selectActivityUnroutineRule(activityUnroutineInDTO);
////		List<ActivityUnroutineShopPlus> activityUnroutineShopPlusList = activityUnroutineShopPlusMapper.selectActivityUnroutineShopPlusList(id);
//		activityUnroutineOutDTO.setActivityUnroutineRuleList(activityUnroutineRuleList);
////		activityUnroutineOutDTO.setActivityUnroutineShopPlusList(activityUnroutineShopPlusList);
//		return activityUnroutineOutDTO;
//	}

	@Override
	public BaseOutDTO changeMaxAmount(Map<String, Integer> param) {
		BaseOutDTO baseOutDTO = new BaseOutDTO();
		Long id = (long)param.get("id");
		Integer maxAmount = (Integer) param.get("maxAmount");
		int i = activityBaseMapper.updateMaxAmount(id, maxAmount);
		if(i == 1) {
			baseOutDTO.setErrorCode(Rescode.SUCCESS);
		} else {
			baseOutDTO.setErrorCode(Rescode.FAIL);
		}
		return baseOutDTO;
	}

	@Override
	public ActivityParticipationOutListDTO listPageParticipation(ActivityParticipationQueryDTO activityParticipationQueryDTO) {
		ActivityParticipationOutListDTO activityParticipationOutListDTO = new ActivityParticipationOutListDTO();

		Integer activityType = activityParticipationQueryDTO.getActivityType();
		int sendType = activityParticipationQueryDTO.getSendType();
		long activityId = activityParticipationQueryDTO.getId();

		long attendTimes, attendPeoples;
		List<ActivityParticipationOutDTO> activityParticipationOutDTOList;

		if(activityType == 2) {
			attendTimes = tradeOfflineMapper.countRechargeParticipationTimes(activityId);
			attendPeoples = tradeOfflineMapper.countRechargeParticipationPeoples(activityId);
			activityParticipationOutDTOList = tradeOfflineMapper.listPageRechargePraticipation(activityParticipationQueryDTO);
		} else {
			if(sendType == ActivityEnum.ActivitySendType.Cash.getType()) {
				attendTimes = tradeOfflineMapper.countParticipationTimes(activityParticipationQueryDTO);
				attendPeoples = tradeOfflineMapper.countParticipationPeoples(activityParticipationQueryDTO);
				activityParticipationOutDTOList = tradeOfflineMapper.listPageParticipation(activityParticipationQueryDTO);
			} else if (sendType == ActivityEnum.ActivitySendType.RedPackage.getType()){
				attendTimes = redpackageUserMapper.countParticipationTimes(activityId);
				attendPeoples = redpackageUserMapper.countParticipationPeoples(activityId);
				activityParticipationOutDTOList = redpackageUserMapper.listPageParticipation(activityParticipationQueryDTO);
			} else if (sendType == ActivityEnum.ActivitySendType.Coupon.getType()) {
				attendTimes = couponUserMapper.countParticipationTimes(activityId);
				attendPeoples = couponUserMapper.countParticipationPeoples(activityId);
				activityParticipationOutDTOList = couponUserMapper.listPageParticipation(activityParticipationQueryDTO);
			} else {
				attendTimes = bonusSendLogMapper.countParticipationTimes(activityId);
				attendPeoples = bonusSendLogMapper.countParticipationPeoples(activityId);
				activityParticipationOutDTOList = bonusSendLogMapper.listPageParticipation(activityParticipationQueryDTO);
			}
		}

		activityParticipationOutListDTO.setActivityParticipationOutDTOList(activityParticipationOutDTOList);
		activityParticipationOutListDTO.setAttendTimes(attendTimes);
		activityParticipationOutListDTO.setAttendPeoples(attendPeoples);
		activityParticipationOutListDTO.setPage(activityParticipationQueryDTO.getPage());
		return activityParticipationOutListDTO;
	}

	@Override
	public ActivityParticipationDetailOutDTO activityParticipationDetail(Long id, Integer sendType) {
		ActivityParticipationDetailOutDTO activityParticipationDetailOutDTO = new ActivityParticipationDetailOutDTO();
		Map<String, Object> userInfo = null;
		TradeOffline tradeOffline;
		List<Map<String, Object>> sendInfo = null;

		if(sendType == ActivityEnum.ActivitySendType.Cash.getType()) {
			userInfo = tradeOfflineMapper.getConsumerUserInfo(id);
		} else if (sendType == ActivityEnum.ActivitySendType.RedPackage.getType()){
			userInfo = redpackageUserMapper.getUserInfo(id);
			sendInfo = redpackageUserMapper.listOrderSendRedpackage(id);
		} else if (sendType == ActivityEnum.ActivitySendType.Coupon.getType()) {
			userInfo = couponUserMapper.getUserInfo(id);
			sendInfo = couponUserMapper.listOrderSendCoupon(id);
		} else {
			userInfo = bonusSendLogMapper.getUserInfo(id);
		}

		long tradeOfflineId = (long) userInfo.get("tradeOfflineId");
		tradeOffline = tradeOfflineMapper.selectByPrimaryKey(tradeOfflineId);

		activityParticipationDetailOutDTO.setSendInfo(sendInfo);
		activityParticipationDetailOutDTO.setUserInfo(userInfo);
		activityParticipationDetailOutDTO.setTradeOffline(tradeOffline);
		return activityParticipationDetailOutDTO;
	}

	@Override
	public BaseOutDTO overUnroutineActivity(ActivityUnroutineInDTO activityUnroutineInDTO) {
		BaseOutDTO baseOutDTO = new BaseOutDTO();
		ActivityBase activityBase = new ActivityBase();
		activityBase.setId(activityUnroutineInDTO.getId());
		activityBase.setStatus(activityUnroutineInDTO.getStatus());
		int i = activityBaseMapper.updateByPrimaryKeySelective(activityBase);
		if(i == 1) {
			baseOutDTO.setErrorCode(Rescode.SUCCESS);
		} else {
			baseOutDTO.setErrorCode(Rescode.FAIL);
		}
		return baseOutDTO;
	}


	public int insertUnroutineSend(Long memberId, Long orderId,Integer activityPlatformType,Map<String, Object> map) throws Exception{
        int result =0;

        //线上
        if(ActivityEnum.ActivityPlatformType.fromType(activityPlatformType) == ActivityEnum.ActivityPlatformType.OnLine){
        	result = unroutineOnlineSend(memberId,orderId,map);
        }//线下
        else if(ActivityEnum.ActivityPlatformType.fromType(activityPlatformType) == ActivityEnum.ActivityPlatformType.OffLine){

		}

        return result;
	}

	@Override
	public ActivitySelectiveListOutDTO activitySelective(ActivitySelectiveQueryDTO activitySelectiveQueryDTO) {
		ActivitySelectiveListOutDTO activitySelectiveListOutDTO = new ActivitySelectiveListOutDTO();
		Long total = activityUnroutineMapper.countActivitySelective(activitySelectiveQueryDTO);
		activitySelectiveListOutDTO.setTotal(total);
		List<ActivitySelectiveOutDTO> activitySelectiveOutDTOList = activityUnroutineMapper.listActivitySelective(activitySelectiveQueryDTO);
		activitySelectiveListOutDTO.setActivitySelectiveOutDTOList(activitySelectiveOutDTOList);
		activitySelectiveListOutDTO.setErrorCode(Rescode.SUCCESS);
		return activitySelectiveListOutDTO;
	}

	//线上交易
	private int unroutineOnlineSend(Long memberId, Long orderId,Map<String, Object> map) throws Exception{
		int result =0;
		OrderServiceGood order = orderServiceGoodMapper.selectByPrimaryKey(orderId);
		//TradeOffline tradeOnline = tradeOfflineMapper.selectByPrimaryKey(order.getId());
		TradeOffline tradeOffline = tradeOfflineMapper.selectTransactionByTradeNo(order.getOrderNo());
		Member member = memberMapper.selectByPrimaryKey(memberId);

		//获取可用活动规则
		Map<String,Object> param=new HashMap<String,Object>();
		param.put("groupId", member.getGroupId());
		param.put("activityType", ActivityEnum.UnRoutineActivityType.ConsumeSend.getType());
		param.put("activityPlatformType", ActivityEnum.ActivityPlatformType.OnLine.getType());
		param.put("payAmount", tradeOffline.getRealAmount());//实付金额
		param.put("userGrade", member.getGradeId());
		param.put("goodId", order.getGoodId());

		ActivityUnroutineRule rule = activityUnroutineRuleMapper.getCanUsedActivity(param);
		if(rule ==null)
			return -1;

		List<Map<String,Object>> activityList = new ArrayList<Map<String, Object>>();
		Map<String, Object> activityMap = new HashMap<String, Object>();
		activityMap.put("activity_id",rule.getActivityId());
		activityMap.put("activity_name",rule.getActivityName());
		activityMap.put("send_type",ActivityEnum.ActivitySendType.fromType(rule.getSendType()).getName());
		switch (ActivityEnum.ActivitySendType.fromType(rule.getSendType())){
			case Cash:
				Integer backAmt = 0;
				if (rule.getBackMoneyMode() == ActivityEnum.BackMoneyMode.FiexedAmount.getType()) {
					backAmt = rule.getFaceValue();
				}else if(rule.getBackMoneyMode() == ActivityEnum.BackMoneyMode.Percentage.getType()){
					backAmt = rule.getFaceValue()*tradeOffline.getRealAmount()/100;
				}
                if(backAmt > 0) {
					result = activityBaseService.insertSendCashOnline(member, backAmt, rule.getActivityId());
					if(result==1) {
						activityMap.put("backcash_amount", AmountUtils.changeF2Y(String.valueOf(backAmt)));
					}
				}
				break;
			case RedPackage:
				try {
					result = redPackageUserService.sendOneMemberRedPackage(memberId, rule.getRedpackageId(),
							rule.getActivityId(), ActivityEnum.RedPackageGetType.ConsumeSend.getType(), null);
				}catch (Exception ae){
					logger.error(ae);
				}
				if(result==1){
					activityMap.put("redpackage_id",rule.getRedpackageId());
					activityMap.put("redpackage_name",rule.getRedpackageName());
				}
				break;
			case Coupon:
				try {
					rule.setCouponCount(rule.getCouponCount() == null ? 0 : rule.getCouponCount());
					List<Map<String,Object>> couponList = new ArrayList<Map<String, Object>>();
					for (int i = 0; i < rule.getCouponCount(); i++) {
						try {
							result = couponUserService.sendOneMemberCoupon(memberId, Long.parseLong(rule.getCouponId()),
									rule.getActivityId(), ActivityEnum.RedPackageGetType.ConsumeSend.getType(), null);
						}catch (Exception ae){
							logger.error(ae);
						}
						if(result==1) {
							Map<String, Object> couponMap = new HashMap<String, Object>();
							couponMap.put("coupon_id", rule.getCouponId());
							couponMap.put("coupon_name", rule.getCouponName());
							couponList.add(couponMap);
						}
					}
					if(couponList.size()>0)
						activityMap.put("coupon_list",couponList);
				}catch (Exception ex){
					logger.error(ex);
				}
				break;
			default:
				break;
		}
		activityList.add(activityMap);
		if(activityList.size()>0)
			map.put("activity_list",activityList);

		return result;
	}


	//结束动态活动
	public int endUnroutineActivity(Long activityId) throws Exception{
		DefaultTransactionDefinition def = new DefaultTransactionDefinition();
		def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); // 事物隔离级别，开启新事务
		TransactionStatus status = transactionManager.getTransaction(def); // 获得事务状态

		int result =0;

		try {
			ActivityBase activityBase = new ActivityBase();
			activityBase.setId(activityId);
			activityBase.setGmtModified(new Date());
			activityBase.setStatus(ActivityEnum.ActivityStatus.Over.getType());
			activityBaseMapper.updateByPrimaryKeySelective(activityBase);
			//获取更新后的记录
			ActivityBase record = activityBaseMapper.selectByPrimaryKey(activityId);

			//计算解冻金额
			Integer unfreezeAmount = (record.getMaxAmount() == null ? 0 : record.getMaxAmount()) -
					(record.getUsedAmount() == null ? 0 : record.getUsedAmount());
			if (unfreezeAmount > 0) {
				//解冻营销账户冻结金额
				groupAccountService.updateAmount(record.getGroupId(),
						BizEnum.SaleAccountSubjectType.ConsumeBackCashUnfreeze, unfreezeAmount, record.getId(), record.getId(), "动态活动解冻");
			}
			activityUnroutineMapper.updateUnroutineActivityMoneyBack(activityId);
			transactionManager.commit(status);
		}catch (Exception e) {
			transactionManager.rollback(status);
			throw e;
		}

		return result;

	}

	public void endAllExpireUnroutineActivity() throws Exception{

		List<ActivityUnroutine> activityUnroutines = activityUnroutineMapper.selectAllExpireUnroutineActivityList();
		for(ActivityUnroutine activityUnroutine:activityUnroutines){
			endUnroutineActivity(activityUnroutine.getActivityId());
		}

	}
}
